import { KeyStores } from '@app/storage/keystore'

class Accounts {
    private tronWeb: any
    private accounts: Set<string>

    constructor(tronWeb: any) {
        this.tronWeb = tronWeb
        this.accounts = new Set()
    }

    /**
     * 创建新地址
     * @returns address
     */
    async create() {
        const account = await this.tronWeb.createAccount()
        await KeyStores.insert(account.address.base58, account.privateKey)
        this.accounts.add(account.address.base58)
        return account.address.base58
    }

    /**
     * 是否为本地地址
     * @param address - 地址
     */
    has(address: string) {
        return this.accounts.has(address)
    }

    /**
     * 获取本地地址列表
     * @param address - 地址
     */
    getAccounts() {
        const accounts = new Array<string>()
        this.accounts.forEach((address: string) => accounts.push(address))
        return accounts
    }

    /**
     * 加载所有帐户地址
     * @param address 
     * @returns 
     */
    async loadAccounts() {
        let offset = 0
        const limit = 10000
        while (true) {
            const keys = await KeyStores.scan(offset, limit)
            keys.forEach((key => {
                this.accounts.add(key.address)
            }))
            if (keys.length < limit) {
                break
            }
            offset += limit
        }
        return this.accounts.size
    }

    /**
     * 获取地址私钥
     * @param address - 地址
     */
    async getPrivateKey(address: string) {
        if (!this.accounts.has(address)) {
            return
        }

        const keystore = await KeyStores.get(address)
        if (!keystore) {
            return
        }
        return keystore.privateKey
    }
}

export { Accounts }
